﻿using System;
using Top.Api.Stream.Message;
using Top.Api.Domain;

namespace Top.Api.Sync
{
    public class TopCometMessageListener : ITopCometMessageListener
    {
        private TopApiService topApiService;

        public TopCometMessageListener(TopApiService topApiService)
        {
            this.topApiService = topApiService;
        }

        public void OnClientKickOff()
        {
        }

        public void OnConnectMsg(string message)
        {
        }

        public void OnConnectReachMaxTime()
        {
        }

        public void OnDiscardMsg(string message)
        {
        }

        public void OnException(Exception ex)
        {
        }

        public void OnHeartBeat()
        {
        }

        public void OnOtherMsg(string message)
        {
        }

        public void OnReceiveMsg(string message)
        {
            object obj = MessageDecode.DecodeMsg(message);
            if (obj.GetType() == typeof(NotifyTopats))
            {
                Console.WriteLine(message);
                NotifyTopats nt = obj as NotifyTopats;
                if ("done".Equals(nt.TaskStatus))
                {
                    string url = topApiService.GetTaskResultUrl(nt.TaskId);
                    if (url != null)
                    {
                        topApiService.DownloadAndProcess(url);
                    }
                }
            }
            else if (obj.GetType() == typeof(NotifyTrade))
            {
                NotifyTrade nt = obj as NotifyTrade;
                Console.WriteLine(nt.SellerNick + ":" + nt.Tid); // FIXME 获取订单详情并保存到数据库
            }
        }

        public void OnServerKickOff()
        {
        }

        public void OnServerRehash()
        {
        }

        public void OnServerUpgrade(string message)
        {
        }
    }
}
